import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbtheteacherisqualifiedforthecurriculum } from '../../../../atoms/db';

const logger = anylogger('pages/api/zllweapp/employmentcourse/s001.api');

export type Result = {
	ok: true;
	data1: {
		professionalname: string;
		sub: Array<string>;
	}[]
} | {
	ok: false;
	message: string;
};

export type Message = {

}

/**
 * pages/api/zllweapp/employmentcourse/s001.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		//**获取登录教师id */
		const teach_id = 'T001';

		//** 此处查询coursename应该关联字段，后期需调整 */
		const data = await tbtheteacherisqualifiedforthecurriculum()
			.select({
				professionalname: 'theteacherisqualifiedforthecurriculum.professionalname',
				coursename: 'curriculum.coursename'
			})
			.where({
				teacher_id: teach_id
			})
			.leftJoin(
				'curriculum', 'curriculum.curriculum_id', 'theteacherisqualifiedforthecurriculum.curriculum_id',
			);


		const data1 = data.reduce((pre, it1): any => {
			const item = pre.find((it2) => {
				return it1.professionalname === it2.professionalname;
			});
			console.log('item', item);
			if (item) {
				item.sub.push(it1.coursename);
			}
			else {
				pre.push({ professionalname: it1.professionalname, sub: [it1.coursename] });
			}
			return pre;
		},
			[] as Array<{ professionalname: string; sub: Array<string> }>);


		logger.debug('data1', data1);

		logger.debug('data', data);

		res.status(200).json({ ok: true, data1 });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
